package com.cms.entity;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.annotation.JSONField;
import com.baomidou.mybatisplus.annotation.TableField;
import com.baomidou.mybatisplus.annotation.TableName;
import com.baomidou.mybatisplus.extension.toolkit.SqlRunner;
import com.cms.domain.Config;
import com.cms.entity.base.BaseCategory;
import com.cms.enums.ModelType;
import com.cms.utils.SystemUtils;
import lombok.EqualsAndHashCode;
import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Entity - 内容栏目
 * 
 * 
 * 
 */
@SuppressWarnings("serial")
@EqualsAndHashCode(callSuper = false)
@TableName("cms_category")
public class Category extends BaseCategory {
	
	/** 树路径分隔符 */
	public static final String TREE_PATH_SEPARATOR = ",";

	/**
	 * 模型
	 */
	@TableField(exist=false)
	@JSONField(serialize=false)  
	private Model model;
	
	/**
	 * 内容
	 */
	@TableField(exist=false)
	@JSONField(serialize=false)  
	private List<Content> contents;
	
	/**
	 * 下级分类
	 */
	@TableField(exist=false)
	@JSONField(serialize=false)  
	private List<Category> children;
	
	/**
	 * 上级分类
	 */
	@TableField(exist=false)
	@JSONField(serialize=false)  
	private Category parent;
	
	/**
	 * 获取模型
	 * @return	模型
	 */
	public Model getModel(){
		if(model == null){
			Map<String,Object> map = SqlRunner.db().selectOne("select * from cms_model where id={0}",getModelId());
			model = JSON.parseObject(JSON.toJSONString(map), Model.class);
		}
		return model;
	}

	/**
	 * 获取内容
	 * 
	 * @return 内容
	 */
	public List<Content> getContents(){
	    if(contents == null){
			List<Map<String,Object>> maps = SqlRunner.db().selectList("select * from cms_content where categoryId = {0}",getId());
			contents = maps.stream().map(i->JSON.parseObject(JSON.toJSONString(i), Content.class)).collect(Collectors.toList());
	    }
		return contents;
	}
	
	/**
	 * 获取下级分类
	 * 
	 * @return 下级分类
	 */
	public List<Category> getChildren() {
	    if(children == null){
			List<Map<String,Object>> maps = SqlRunner.db().selectList("select * from cms_category where parentId={0} order by sort desc",getId());
	        children = maps.stream().map(i-> JSON.parseObject(JSON.toJSONString(i), Category.class)).collect(Collectors.toList());
	    }
		return children;
	}
	
	/**
	 * 获取上级分类
	 * @return	上级分类
	 */
	public Category getParent(){
	    if(parent == null){
			Map<String,Object> map = SqlRunner.db().selectOne("select * from cms_category where id={0}",getParentId());
			parent = JSON.parseObject(JSON.toJSONString(map), Category.class);
	    }
		return parent;
	}
	

	
	/**
	 * 获取所有上级分类ID
	 * 
	 * @return 所有上级分类ID
	 */
	public Integer[] getParentIds() {
		String[] treePaths = StringUtils.split(getTreePath(), TREE_PATH_SEPARATOR);
		Integer[] result = new Integer[treePaths.length];
		for (int i = 0; i < treePaths.length; i++) {
			result[i] = Integer.valueOf(treePaths[i]);
		}
		return result;
	}
	

	
	
	/**
	 * 设置值
	 * 
	 */
	public void setValue() {
		if (getParentId() != null) {
			setTreePath(getParent().getTreePath() + getParent().getId() + TREE_PATH_SEPARATOR);
		} else {
			setTreePath(TREE_PATH_SEPARATOR);
		}
		setGrade(getParentIds().length);
	}
	
	/**
	 * 获取文本内容
	 * 
	 * @return 文本内容
	 */
	public String getText() {
		if (StringUtils.isEmpty(getIntroduction())) {
			return StringUtils.EMPTY;
		}
		return Jsoup.parse(getIntroduction()).text();
	}
	
   /**
     * 获取第一张图片
     * 
     * @return 第一张图片
     */
    public String getFirstImage(){
        Elements elements = Jsoup.parse(getIntroduction()).getElementsByTag("img");
        if(elements!=null && elements.size()>0){
            Element element = elements.get(0);
            return element.attr("src");
        }
        return null;
    }
	
	
	/**
	 * 获取路径
	 * 
	 * @return 路径
	 */
	public String getPath() {
	    if(StringUtils.isNotBlank(getOutlink())){
            return getOutlink();
        }
	    Config config = SystemUtils.getConfig();
		if(config.getSiteModel()==Config.SiteModel.DYNAMIC.ordinal()){
	    	return getDynamicPath(null);
		}
	    return getHtmlPath(null);
	}

	/**
	 * 获取路径
	 *
	 * @return 路径
	 */
	public String getPagePath(Integer pageNumber) {
		Config config = SystemUtils.getConfig();
		if(config.getSiteModel()==Config.SiteModel.DYNAMIC.ordinal()){
			return getDynamicPath(pageNumber);
		}
		return getHtmlPath(pageNumber);
	}

	/**
	 * 获取动态路径
	 *
	 * @return 动态路径
	 */
	public String getDynamicPath(Integer pageNumber){
		Map<String,Object> map = SqlRunner.db().selectOne("select * from cms_site where id={0}",getSiteId());
		Site site = JSON.parseObject(JSON.toJSONString(map), Site.class);
		String siteUrl = site.getUrl();
		String categoryCat = getCat();
		String pageNumberUrl = "";
		if(pageNumber !=null){
			pageNumberUrl = "_"+pageNumber;
		}
		return siteUrl+"/"+categoryCat+pageNumberUrl;
	}

	/**
	 * 获取静态路径
	 *
	 * @return 静态路径
	 */
	public String getHtmlPath(Integer pageNumber) {
		Map<String,Object> map = SqlRunner.db().selectOne("select * from cms_site where id={0}",getSiteId());
		Site site = JSON.parseObject(JSON.toJSONString(map), Site.class);
		String siteUrl = site.getUrl();
		String categoryCat = getCat();
		String pageNumberUrl = "";
		if(pageNumber !=null){
			pageNumberUrl = "_"+pageNumber;
		}
		return siteUrl+"/"+categoryCat+pageNumberUrl+".html";
	}

	/**
	 * 获取pc模板路径
	 *
	 * @return 模板路径
	 */
	public String getPcTemplatePath() {
		Map<String,Object> map = SqlRunner.db().selectOne("select * from cms_site where id={0}",getSiteId());
		Site site = JSON.parseObject(JSON.toJSONString(map), Site.class);
		if(StringUtils.isBlank(site.getPcTemplate())){
			return null;
		}
		if(getModel().getType()== ModelType.LIST.ordinal()){
			if(StringUtils.isBlank(getListTemplate())){
				return null;
			}
			return "templates/"+site.getPcTemplate()+"/"+getListTemplate();
		}else if(getModel().getType()== ModelType.PAGE.ordinal()){
			if(StringUtils.isBlank(getDetailTemplate())){
				return null;
			}
			return "templates/"+site.getPcTemplate()+"/"+getDetailTemplate();
		}else{
			return null;
		}
	}

	/**
	 * 获取mobile模板路径
	 *
	 * @return 模板路径
	 */
	public String getMobileTemplatePath() {
		Map<String,Object> map = SqlRunner.db().selectOne("select * from cms_site where id={0}",getSiteId());
		Site site = JSON.parseObject(JSON.toJSONString(map), Site.class);
		if(StringUtils.isBlank(site.getMobileTemplate())){
			return null;
		}
		if(getModel().getType()== ModelType.LIST.ordinal()){
			if(StringUtils.isBlank(getListTemplate())){
				return null;
			}
			return "templates/"+site.getMobileTemplate()+"/"+getListTemplate();
		}else if(getModel().getType()== ModelType.PAGE.ordinal()){
			if(StringUtils.isBlank(getDetailTemplate())){
				return null;
			}
			return "templates/"+site.getMobileTemplate()+"/"+getDetailTemplate();
		}else{
			return null;
		}
	}
}
